#!/usr/bin/env python3

import dash
import flask
import dash_bootstrap_components as dbc

from . import styles

dash.register_page(__name__, path="/")

login_card = dbc.Card(
  dbc.CardBody([
    dash.html.H1(dash.html.B("Score Managing System"), className="text-center mt-4 mb-5"),
    dash.html.Div([
      dbc.FormFloating([
        dbc.Input(type="username", id="username", placeholder="Enter username"),
        dbc.Label("Username", html_for="username"),
        dbc.FormText(
          "By default username is the same as your own name",
          color="secondary",
        ),
      ]),
      dbc.FormFloating([
        dbc.Input(type="password", id="password", placeholder="Enter password"),
        dbc.Label("Password", html_for="password"),
        dbc.Button("Login", id="login_button", color="success", className="d-grid gap-2 col-6 mx-auto"),
      ]),
    ]),
    dash.html.Div(
      dbc.Alert("Your username or password is not right! Try it again!", id="error", dismissable=True, color="danger", style=styles.hidden_style)
    ),
  ]),
  outline=False,
  style=styles.center_card_style
)

layout = dbc.Container([
  dash.dcc.Location(id="login_url", refresh=True), dbc.Row(login_card)
])

@dash.callback([dash.Output("error", "style"), dash.Output("login_url", "href")],
               dash.Input("login_button", "n_clicks"),
               [dash.State("username", "value"), dash.State("password", "value")],
               prevent_initial_call=True)
def login(n_clicks, username, password):
  from .utils import db_opt as do

  if n_clicks is None:
    raise dash.exceptions.PreventUpdate

  user_info = do.DatabaseOperation().login(username, password)
  if user_info is None:
    return styles.display_style, dash.no_update

  return dash.no_update, "/{}/{}".format(user_info.type, user_info.id)
